from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session
import logging
import os

from app.models.database import Base

logger = logging.getLogger(__name__)

# 使用SQLite数据库
DATABASE_URL = "sqlite:///./crawl4ai.db"

# 创建数据库引擎
engine = create_engine(
    DATABASE_URL,
    echo=False,  # 设为True可以看到SQL语句
    connect_args={"check_same_thread": False}
)

# 创建会话工厂
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

def init_db():
    """初始化数据库"""
    try:
        Base.metadata.create_all(bind=engine)
        logger.info("Database initialized successfully")
    except Exception as e:
        logger.error(f"Failed to initialize database: {e}")
        raise

def close_db():
    """关闭数据库连接"""
    try:
        engine.dispose()
        logger.info("Database connections closed")
    except Exception as e:
        logger.error(f"Error closing database connections: {e}")

def get_db_session() -> Session:
    """获取数据库会话"""
    db = SessionLocal()
    try:
        yield db
    except Exception as e:
        db.rollback()
        logger.error(f"Database session error: {e}")
        raise
    finally:
        db.close()
        except Exception as e:
            await session.rollback()
            logger.error(f"Database session error: {e}")
            raise
        finally:
            await session.close()
